#!/usr/bin/env python

import sys
import os

# Here are the email pacakge modules we'll need
import email.MIMEText
import email.MIMEBase
import email.MIMEMultipart
import email

import optparse
import mimetypes

import smtplib
import string
        
def username():
    return os.environ.get('USER', os.environ.get('LOGNAME', os.environ['USERNAME']))


def getMimeTypeFromFilename(filename):
    guess = mimetypes.guess_type(filename)
    if guess[0] is None:
        return (('application', 'octet-stream'))
    else:
        return guess[0].split('/')
    

class MailSender:
    def send(self, fromAddress, toAddresses, subject, body, files):
        if ( type(toAddresses) == type("") ):
            toAddresses = [toAddresses];
           
        msg = email.MIMEMultipart.MIMEMultipart()


        msg['Subject'] = subject
        msg['To'] = string.join(toAddresses, ', ')
        msg.preamble = 'This is the preamble'
        msg.epilogue = ''

        msg.attach(email.MIMEText.MIMEText(body))

        for file in files:
            (baseType, subtype) = getMimeTypeFromFilename(file)

            part = email.MIMEBase.MIMEBase(baseType, subtype)
            part.set_payload( open(file,"rb").read() )

            email.Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"'
                           % os.path.basename(file))
            msg.attach(part)

        s = smtplib.SMTP()
        s.connect('mailhost')
        s.sendmail(fromAddress, toAddresses, msg.as_string())
        s.close()

def main(args=None):
    if args is None:
        args = sys.argv[1:]

    if len(args) < 3:
        print 'Usage:', os.path.basename(sys.argv[0]), 'mail <subject> <body> <inputFile> <to> [<to> ...]'
        return 1
    
    subject = args[0]
    body = file(args[1]).read()
    inputFileName = args[2]
    toAddresses = args[3:]

    m = MailSender()
    m.send(username() + '@mitra.com',  toAddresses, subject, body, [inputFileName])
    
    return 0


if __name__ == '__main__':
    sys.exit(main())

